package zgrjb.snbq.teach_platform.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import zgrjb.snbq.teach_platform.config.SmsConfig;


@Slf4j
@Component
public class SmsComponent {

    /**
     * 发送地址
     */
    private static final String URL_TEMPLATE = "https://zwp.market.alicloudapi.com/sms/sendv2mobile=%s&content=%s";

    private static final String CONTENT = "【智能教学平台】您的验证码是%s。如非本人操作，请忽略本短信";


    @Autowired
    private SmsConfig smsConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送短信验证码
     * @param to 手机号
     * @param code 验证码
     */
    public void send(String to, String code) {
        log.info("📱 准备发送短信验证码到: {}, 验证码: {}", to, code);
        
        // 检查短信配置
        if (smsConfig == null) {
            log.warn("⚠️ SmsConfig为null，使用模拟短信");
            simulateSms(to, code);
            return;
        }
        
        String appCode = smsConfig.getAppCode();
        log.info("📋 当前短信配置 - appCode: {}", appCode != null ? appCode.substring(0, Math.min(8, appCode.length())) + "..." : "null");
        
        if (!StringUtils.hasText(appCode)) {
            log.warn("⚠️ 短信服务appCode未配置或为空，使用模拟短信");
            simulateSms(to, code);
            return;
        }

        try {
            // 真实短信发送
            String host = "https://zwp.market.alicloudapi.com/sms/sendv2";
            
            log.info("📱 开始发送真实短信验证码到: {}", to);
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "APPCODE " + appCode);
            headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            
            // 设置请求参数
            MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
            map.set("mobile", to);
            map.set("content", "【智能云】您的验证码是" + code + "。如非本人操作，请忽略本短信");
            
            HttpEntity<Object> http = new HttpEntity<>(map, headers);
            String result = restTemplate.postForObject(host, http, String.class);
            
            log.info("📱 短信发送响应: {}", result);
            
            if (result != null && (result.contains("success") || result.contains("\"success\":true"))) {
                log.info("✅ 真实短信验证码发送成功到: {}", to);
            } else {
                log.error("❌ 真实短信验证码发送失败: {}", result);
                // 发送失败时，降级为模拟短信
                log.warn("⚠️ 真实短信发送失败，降级为模拟短信");
                simulateSms(to, code);
            }
            
        } catch (Exception e) {
            log.error("❌ 短信发送异常: {}", e.getMessage(), e);
            // 发送失败时，降级为模拟短信
            log.warn("⚠️ 短信发送异常，降级为模拟短信");
            simulateSms(to, code);
        }
    }
    
    /**
     * 模拟短信发送
     */
    private void simulateSms(String to, String code) {
        log.info("📱 [模拟短信] 发送到: {}, 验证码: {}", to, code);
        log.info("📱 [模拟短信] 内容: 【智能云】您的验证码是{}。如非本人操作，请忽略本短信", code);
        log.info("🔔 请在前端输入验证码: {}", code);
    }
}
